package com.crois.barrier.web.exception;



import com.crois.barrier.common.exception.BarrierException;
import com.crois.barrier.common.exception.BarrierExceptionEnum;
import com.crois.barrier.common.response.BarrierResponseEntity;
import com.crois.barrier.web.resp.BarrierResponseWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import reactor.retry.RetryExhaustedException;

import java.util.concurrent.TimeoutException;


@Slf4j
@Component
public class BarrierExceptionHandlerAdvice {

    @ExceptionHandler(value = {BarrierException.class})
    public BarrierResponseEntity<Void> handle(BarrierException ex) {
        log.error("网关异常code:{},msg:{}", ex.getCode(),ex.getMessage());
        return BarrierResponseWrapper.fail(ex);
    }
    @ExceptionHandler(value = {Throwable.class})
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public BarrierResponseEntity<Void> handle(Throwable throwable) {

        if(throwable instanceof BarrierException) {
            return handle((BarrierException) throwable);
        }else if (throwable instanceof TimeoutException){
            return BarrierResponseWrapper.fail(BarrierExceptionEnum.BARRIER_GATEWAY_TIMEOUT_FAIL);
        }else if (throwable instanceof RetryExhaustedException){
            return BarrierResponseWrapper.fail(BarrierExceptionEnum.BARRIER_GATEWAY_FAIL);
        }
        return BarrierResponseWrapper.fail(BarrierExceptionEnum.BARRIER_GATEWAY_FAIL);
    }
}
